﻿using Mina.Core.Buffer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using static SharpIM.HttpRequest;

namespace SharpIM
{
    class IoBufferUtil
    {
        public static bool ReadUntil(ref int offset, IoBuffer input, char untilValue, out string str)
        {
            str = "";
            char value;
            while (input.HasRemaining)
            {
                if ((value = input.GetString(1, Encoding.UTF8)[0]) != untilValue)
                {
                    str += value;
                    offset++;
                }
                else
                {
                    offset++;
                    return true;
                }
            }
            return false;
        }
        public static bool ReadUntil(ref int offset, IoBuffer input, string untilValue, out string str)
        {
            str = "";
            string value;
            while (input.HasRemaining)
            {
                value = input.GetString(1, Encoding.UTF8);
                str += value;
                offset++;
                if (str.Length >= untilValue.Length && str.EndsWith(untilValue))
                {
                    str = str.Substring(0, str.Length - untilValue.Length);
                    return true;
                }
            }
            return false;
        }
        public static bool ReadUntil(ref int offset, IoBuffer input, string untilValue, int maxSize, ParserError error, out string str)
        {
            str = "";
            string value;
            int start = offset;
            while (input.HasRemaining)
            {
                value = input.GetString(1, Encoding.UTF8);
                str += value;

                offset++;
                if (offset - start > maxSize)
                {
                    throw new ParserReachSizeLimitException(error);
                }
                if (str.Length >= untilValue.Length && str.EndsWith(untilValue))
                {
                    str = str.Substring(0, str.Length - untilValue.Length);
                    return true;
                }
            }
            return false;
        }
    }

}
